# encoding = utf-8
class DealsController < ApplicationController

  before_filter :authenticate_admin!, :only => [:list, :status]
  before_filter :authenticate_user!, :only => [:new, :create]

  def new
    @user = current_user
    if @user.info.nil?
      redirect_to '/infos/new/deal'
    else
      @carts = @user.carts
    end
  end

  def create
    carts = current_user.carts

    voucher = nil
    
    if !params[:id].nil?
      voucher = current_user.vouchers.where(:money => params[:id]).first
      if voucher.nil?
        flash[:error] = '您没有此面额的代金券'
        redirect_to '/deals/new'
        return
      end
    end
    
    deal = Deal.new({
        :user_id => current_user.id,
        :amount => amount(carts,voucher),
        :kind => DEAL_KIND_COD,
        :status => DEAL_STATUS_WT
      })
    
    if deal.save
      carts.each do |cart|
        product = cart.product
        if product.stock >= cart.number
          Order.create({
              :deal_id => deal.id,
              :product_id => product.id,
              :number => cart.number,
              :price => product.price,
              :discount => product.discount
            })
          product.stock -= cart.number
          product.save
          cart.destroy
        else
          flash[:alert] = "忒疯狂了，在你下手的瞬间，有人以迅雷不及掩耳盗铃之势把#{product.name}抢到不够了"
          cart.destroy
          next
        end
        
      end
      if deal.orders.blank?
        deal.destroy
        redirect_to '/home'
        return
      else
        if !voucher.nil?
          current_user.grants.where(:voucher_id => voucher.id).first.destroy
        end
      end
      
      flash[:success] = '订购成功'
      redirect_to '/users/deals'
    else
      flash[:error] = deal.errors
      redirect_to '/carts/show'
    end
  end
  
  #  == admin ====================================================================

  def list
    if params[:id].nil? or params[:id] == 'waiting'
      @action_title = '等待发货的订单'
      status = DEAL_STATUS_WT
      @next_status = DEAL_STATUS_DL
    elsif params[:id] == 'delivering'
      @action_title = '已经发货的订单'
      status = DEAL_STATUS_DL
      @next_status = DEAL_STATUS_OV
    elsif params[:id] == 'awaitingpayment'
      @action_title = '等待线上付款的订单'
      status = DEAL_STATUS_WP
    elsif params[:id] == 'dated'
      @action_title = '过期的订单'
      status = DEAL_STATUS_DA
    elsif params[:id] == 'over'
      @action_title = '交易成功的订单'
      status = DEAL_STATUS_OV
    end
    @deals = Deal.where(:status => status).order('created_at').paginate :page => params[:page], :per_page => PAGE_SIZE
    render :layout => 'admins'
  end

  def change_status
    deal = Deal.find(params[:id])
    if !deal.nil?
      deal.status = params[:format]
      if deal.save
        flash[:success] = '更改订单状态成功'
      else
        flash[:error] = deal.errors
      end
    else
      flash[:error] = '该订单已经不存在'
    end

    redirect_to '/deals/list'
  end

end
